package lc;

import java.util.Arrays;

public class Ex73 {
    class Solution {
        public void setZeroes(int[][] matrix) {
            int m = matrix.length, n = matrix[0].length;
            boolean cow = false, row = false; //记录首行首列是否需要刷为0

            for (int i = 0; i < n; i++) {
                if (matrix[0][i] == 0) {
                    row = true; //首行需要
                    break;
                }
            }
            for (int i = 0; i < m; i++) {
                if (matrix[i][0] == 0) {
                    cow = true; //首列需要
                    break;
                }
            }

            //将最左一列和最上一列作为标志位
            for (int i = 1; i < m; i++) {
                for (int j = 1; j < n; j++) {
                    if (matrix[i][j] == 0) {
                        matrix[i][0] = 0;
                        matrix[0][j] = 0;
                    }
                }
            }
            for (int i = 0; i < m; i++) {
                if (matrix[i][0] == 0) {
                    //若该行首位为0
                    Arrays.fill(matrix[i], 0);
                }
            }

            for (int i = 0; i < n; i++) {
                if (matrix[0][i] == 0) {
                    //若该列首位为0
                    for (int j = 1; j < m; j++) {
                        matrix[j][i] = 0;
                    }
                }
            }
            if (cow) {
                for (int i = 0; i < m; i++) {
                    matrix[i][0] = 0;
                }
            }
            if (row) {
                Arrays.fill(matrix[0], 0);
            }
        }
    }
}
